package com.glodon.paas.account.web.util;

import javax.servlet.http.HttpServletRequest;

import net.oauth.OAuthAccessor;
import net.oauth.OAuthMessage;
import net.oauth.server.OAuthServlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.context.SecurityContextHolder;

import com.glodon.paas.account.security.oauth1.provider.SimpleOAuthProvider;
import com.glodon.paas.account.security.spring.LoginUser;
import com.glodon.paas.exception.PaasServerException;
import com.glodon.paas.exception.PaasServerExceptionFactory;
import com.glodon.paas.util.BeanFactoryUtil;

/**
 * Application Helper
 */
public class SecurityUtils {

    protected static final Logger LOGGER = LoggerFactory.getLogger(SecurityUtils.class);

    public static LoginUser getCurrentUser() {
        if (SecurityContextHolder.getContext() == null || SecurityContextHolder.getContext().getAuthentication() == null) {
            return null;
        } else if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof LoginUser) {
            return (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        }
        return null;
    }
    
	public static String getOwnerId(HttpServletRequest request) throws PaasServerException{
		try {
			OAuthAccessor accessor = null;
			OAuthMessage requestMessage = OAuthServlet.getMessage(request, null);
			SimpleOAuthProvider oauthProvider = (SimpleOAuthProvider)BeanFactoryUtil.getBean("oauthProvider");
	        accessor = oauthProvider.getAccessor(requestMessage);
	        oauthProvider.VALIDATOR.validateMessage(requestMessage, accessor);
	        
			return (String)accessor.getProperty("user");        
		}
		catch (PaasServerException be) {
			throw be;
		}
		catch (Exception e) {
			throw PaasServerExceptionFactory.accessForbidden("Access Forbidden!", e);
		}
	}
}
